package com.qiguliuxing.dts.db.service;

import com.github.pagehelper.PageHelper;
import com.mysql.cj.util.StringUtils;
import com.qiguliuxing.dts.db.dao.DailyOrderMapper;
import com.qiguliuxing.dts.db.domain.DailyOrder;
import com.qiguliuxing.dts.db.domain.DailyOrder.Column;
import com.qiguliuxing.dts.db.domain.DailyOrderExample;
import com.qiguliuxing.dts.db.domain.ProductProduction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class DailyOrderService {
    private static final Logger logger = LoggerFactory.getLogger(DailyOrderService.class);
    Column[] columns = new Column[]{Column.id, Column.showId,Column.customerName, Column.deliveryType, Column.orderCount, Column.useTime, Column.pieces, Column.orderNumber, Column.orderRowNumber, Column.address, Column.consignee, Column.consigneeTelephone, Column.materialBatch, Column.storageWarehouse, Column.notes,Column.deliveryType,Column.splitQuantity,Column.actualCount,Column.arrivalStation
    };
    @Resource
    private DailyOrderMapper dailyOrderMapper;

    @Autowired
    private ProductProductionService productProductionService;


    /**
     * 获取热卖商品
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<DailyOrder> queryById(int offset, int limit) {
        DailyOrderExample example = new DailyOrderExample();
        /*        example.or().andIseffectiveEqualTo(true);*/
        example.setOrderByClause("overdue desc");
        PageHelper.startPage(offset, limit);

        return dailyOrderMapper.selectByExampleSelective(example, columns);
    }

    /**
     * 获取新品上市
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<DailyOrder> queryByNew(int offset, int limit) {
        DailyOrderExample example = new DailyOrderExample();
        example.setOrderByClause("date desc");
        PageHelper.startPage(offset, limit);

        return dailyOrderMapper.selectByExampleSelective(example, columns);
    }

    /**
     * 获取分类下的商品
     *
     * @param catList
     * @param offset
     * @param limit
     * @return
     */
    public List<DailyOrder> queryByid(List<Integer> catList, int offset, int limit) {
        DailyOrderExample example = new DailyOrderExample();
        /*   example.or().andIdIn(catList).andIseffectiveEqualTo(true);*/
        example.setOrderByClause("date  desc");
        PageHelper.startPage(offset, limit);

        return dailyOrderMapper.selectByExampleSelective(example, columns);
    }

    /*开发一个起始日期-结束日期查询功能*/
    public List<DailyOrder> querySelective(String customerName,String startTime,String endTime,/*DailyOrder dailyOrder,*/ Integer page, Integer limit,String sort,String order) {
        DailyOrderExample example = new DailyOrderExample();
        DailyOrderExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isNullOrEmpty(customerName))
            criteria.andCustomerNameLike("%"+customerName+"%");
        /*if (!StringUtils.isNullOrEmpty(dailyOrder.getOrderCount()))
            criteria.andOrderCountEqualTo(dailyOrder.getOrderCount());*/
        /*if (!org.springframework.util.StringUtils.isEmpty(startTime) && !org.springframework.util.StringUtils.isEmpty(endTime)) {*/
        if(!startTime.isEmpty() && !endTime.isEmpty()){
            criteria.andDateBetween(LocalDate.parse(startTime), LocalDate.parse(endTime));
        }
        if (!com.alibaba.druid.util.StringUtils.isEmpty(sort) && !com.alibaba.druid.util.StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return dailyOrderMapper.selectByExample(example);
    }

    /**
     * 获取某个文档,包含完整信息
     *
     * @param id
     * @return
     */
    public DailyOrder findById(Integer id) {
        DailyOrderExample example = new DailyOrderExample();
        /*example.or().andidEqualTo(id).andDeletedEqualTo(false);*/
        example.or().andIdEqualTo(id);
        /* return goodsMapper.selectOneByExampleWithBLOBs(example);*/
        return dailyOrderMapper.selectOneByExampleSelective(example);
    }

    /**
     * 根据文档编号找到商品
     *
     * @param instrumentNumber
     * @return
     */
    public DailyOrder findByinstrumenttype(String instrumentNumber) {
        DailyOrderExample example = new DailyOrderExample();
        /*example.or().andGoodsSnEqualTo(goodsSn).andDeletedEqualTo(false);*/
        /*  example.or().andInstrumentNameEqualTo(instrumentNumber).andIseffectiveEqualTo(false);*/
        return dailyOrderMapper.selectOneByExampleSelective(example);
    }

    /**
     * 获取某个商品信息，仅展示相关内容
     *
     * @param id
     * @return
     */
    public DailyOrder findByIdVO(Integer id) {
        DailyOrderExample example = new DailyOrderExample();
        /*   example.or().andIdEqualTo(id).andIseffectiveEqualTo(true);*/
        return dailyOrderMapper.selectOneByExampleSelective(example, columns);
    }

    public DailyOrder findBySnVO(int instrumentType) {
        DailyOrderExample example = new DailyOrderExample();
        /* example.or().andInstrumentTypeEqualTo(instrumentType).andIseffectiveEqualTo(true);*/
        return dailyOrderMapper.selectOneByExampleSelective(example, columns);
    }

    /**
     * 获取所有在售物品总数
     *
     * @return
     */
    public Integer queryOnSale() {
        DailyOrderExample example = new DailyOrderExample();
        /*        example.or().andIseffectiveEqualTo(true);*/
        return (int) dailyOrderMapper.countByExample(example);
    }

    public int updateById(DailyOrder instrument) {
        /*   instrument.setUpdatetime(LocalDate.now());*/
        return dailyOrderMapper.updateByPrimaryKeySelective(instrument);
    }

    public void deleteById(Integer id) {
        /*dailyOrderMapper.logicalDeleteByPrimaryKey(id);*/
    }

    public void add(DailyOrder instrument) {
        /* instrument.setAddTime(""LocalDate.now()"");*/
        /*instrument.setUpdateTime(LocalDateTime.now());*/
        Random random = new Random(10000052);
        instrument.setId(random.nextInt());

        // 根据订量 计算公式 写入
        // 根据批号查询浓度  然后计算
//        instrument
        ProductProduction productProduction = productProductionService.queryByBatchNumber(instrument.getMaterialBatch());
        if (productProduction != null) {
            // 计算
            float concent = Float.parseFloat(productProduction.getOralConcentration().toString());// 浓度
            if (instrument.getActualCount() != null && !instrument.getActualCount().isEmpty()) {
                float result = (float) (Float.parseFloat(instrument.getActualCount()) / concent * 1.05);
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                String ans_3 = decimalFormat.format(result);
                instrument.setSplitQuantity(ans_3);
            }
        }

        // 把dailyOrder的实体类代码重新生成一下就OK了。。。我先去睡了好的 晚安
        instrument.setPieces(1);

        dailyOrderMapper.insert(instrument);
    }

    /**
     * 获取所有物品总数，包括在售的和下架的，但是不包括已删除的商品
     * 获取所有文档总数。
     *
     * @return
     */
    public int count() {
        DailyOrderExample example = new DailyOrderExample();
        example.or();
        return (int) dailyOrderMapper.countByExample(example);
    }

/*    public List<Integer> getCatIds(Integer brandId, String keywords, Boolean isHot, Boolean isNew) {
        DailyOrderExample example = new DailyOrderExample();
        DailyOrderExample.Criteria criteria1 = example.or();
        DailyOrderExample.Criteria criteria2 = example.or();

        if (!StringUtils.isEmpty(brandId)) {
            criteria1.andBrandIdEqualTo(brandId);
            criteria2.andBrandIdEqualTo(brandId);
        }
        if (!StringUtils.isEmpty(isNew)) {
            criteria1.andIsNewEqualTo(isNew);
            criteria2.andIsNewEqualTo(isNew);
        }
        if (!StringUtils.isEmpty(isHot)) {
            criteria1.andIsHotEqualTo(isHot);
            criteria2.andIsHotEqualTo(isHot);
        }
        if (!StringUtils.isEmpty(keywords)) {
            criteria1.andKeywordsLike("%" + keywords + "%");
            criteria2.andNameLike("%" + keywords + "%");
        }
        criteria1.andIsOnSaleEqualTo(true);
        criteria2.andIsOnSaleEqualTo(true);
        criteria1.andDeletedEqualTo(false);
        criteria2.andDeletedEqualTo(false);

        List<DailyOrder> goodsList = goodsMapper.selectByExampleSelective(example, Column.categoryId);
        List<Integer> cats = new ArrayList<Integer>();
        for (DailyOrder goods : goodsList) {
            cats.add(goods.getCategoryId());
        }
        return cats;
    }*/

    public boolean checkExistByName(String name) {
        DailyOrderExample example = new DailyOrderExample();
        /* example.or().andInstrumentNameEqualTo(name);*/
        return dailyOrderMapper.countByExample(example) != 0;
    }

    /**
     * 根据店铺，获取店铺对应类别的商品
     * 根据文档类型，获取对应文档类型的文档
     * @param brandId
     * @param i
     * @param related
     * @return
     */
/*    public List<DailyOrder> queryByBrandId(int bid, int cid, int offset, int limit) {
        DailyOrderExample example = new DailyOrderExample();
        example.or().andBrandIdEqualTo(bid).andCategoryIdEqualTo(cid).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        example.setOrderByClause("browse desc");
        PageHelper.startPage(offset, limit);

        return dailyOrderMapper.selectByExampleSelective(example, columns);
    }*/

    /**
     * 同类商品，且不同店铺
     *
     * @param brandId
     * @param cid
     * @param i
     * @param limitCid
     * @return
     */
  /*  public List<DailyOrder> queryByCategoryAndNotSameBrandId(int bid, int cid, int offset, int limit) {
        DailyOrderExample example = new DailyOrderExample();
        example.or().andBrandIdNotEqualTo(bid).andCategoryIdEqualTo(cid).andIsOnSaleEqualTo(true)
                .andDeletedEqualTo(false);
        example.setOrderByClause("browse desc");
        PageHelper.startPage(offset, limit);

        return dailyOrderMapper.selectByExampleSelective(example, columns);
    }*/
}
